﻿// SMIL is a community project avaipublic lable under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// View the project and the latest code at http://smil.codeplex.com/

using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

using DeepEarth.BingMapsToolkit.Client.Common;

using Microsoft.Maps.MapControl;
using Microsoft.Maps.MapControl.Core;

using mpost.SilverlightMultiFileUpload.Core;
using SMIL.ApplicationVariables;

namespace SMIL.FileUploadClient
{
    public class FileUpload : Control //, IMapControl<Map>
    {
        const string _FILEUPLOAD = "FILEUPLOAD";

        Configuration configuration;
        FileCollection files;

        Map parentMap;
        public Map ParentMap
        {
            get { return parentMap; }
            set
            {
                if (value != null)
                {
                    parentMap = value;
                    ParentMap.Drop += ParentMap_Drop;
                }
            }
        }

        public MapLayer Uploadlayer { get; set; }
        string uploadService = string.Empty;
        public string SPWeb { get; set; }
        public string DocumentLibrary { get; set; }
        public string CoordinateFieldInDocumentLibrary { get; set; }


        static TextBlock textBlock;

        public FileUpload(Map parentMap, string spWEb, string documentLibrary, string coordinateFieldInDocumentLibrary)
        {

            configuration = new Configuration();
            textBlock = new TextBlock();
            ParentMap = parentMap;
            SPWeb = spWEb;
            DocumentLibrary = documentLibrary;
            CoordinateFieldInDocumentLibrary = coordinateFieldInDocumentLibrary;
            SetInitParameters();

        }

        void SetInitParameters()
        {
            uploadService = string.Concat(SPWeb, "/_layouts/smil/SMIL.MultiFileUpload.ashx");
            string uploadParams = SetUploadParams();
            files = new FileCollection(uploadService, uploadParams, 4);
        }

        private string SetUploadParams()
        {
            string uploadParams = "[DocumentLibrary={0};CoordinateFieldNameInForeignColumn={1}]";
            uploadParams = uploadParams.Replace("{0}", DocumentLibrary);
            uploadParams = uploadParams.Replace("{1}", CoordinateFieldInDocumentLibrary);
            return uploadParams;
        }

        void ParentMap_Drop(object sender, DragEventArgs e)
        {
            FileInfo[] files = (FileInfo[])e.Data.GetData(System.Windows.DataFormats.FileDrop);

            foreach (var item in files)
            {
                if (null == Uploadlayer)
                    Uploadlayer = new MapLayer();

                FileUploadUIControl uploadProgressIcon = new FileUploadUIControl();
                uploadProgressIcon.tbFileName.Text = files[0].Name;
                uploadProgressIcon.UserFile = new UserFile();

                Point droppedFile = e.GetPosition(ParentMap);
                droppedFile.X = droppedFile.X - Convert.ToInt32(uploadProgressIcon.tbFileName.ActualWidth / 2);
                droppedFile.Y = droppedFile.Y - 30;

                Uploadlayer.AddChild(uploadProgressIcon, ParentMap.ViewportPointToLocation(droppedFile));

                if (!ParentMap.Children.Contains(Uploadlayer))
                    ParentMap.Children.Add(Uploadlayer);

                AddFile(item, uploadProgressIcon.UserFile, ParentMap.ViewportPointToLocation(e.GetPosition(ParentMap)));

                //RemoveUploadChildren();
            }
            this.files.UploadFiles();
        }

        private void AddFile(FileInfo file, UserFile userFile, Location location)
        {
            string fileName = file.Name;

            //    //Create a new UserFile object
            userFile.FileName = file.Name;
            userFile.FileStream = file.OpenRead();
            userFile.UIDispatcher = this.Dispatcher;
            userFile.Location = location;
            //userFile.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(userFile_PropertyChanged);
            userFile.Configuration = configuration;


            //    //Check for the file size limit (configurable)

            if (userFile.FileStream.Length <= configuration.MaxFileSize)
            {
                //Add to the list
                files.Add(userFile);
            }
            else
            {
                //MessageChildWindow messageWindow = new MessageChildWindow();
                //messageWindow.Message = UserMessages.MaxFileSize + (configuration.MaxFileSize / 1024).ToString() + "KB.";
                //messageWindow.Show();

                //if (MaximumFileSizeReached != null)
                //    MaximumFileSizeReached(this, null);

            }
        }

        void RemoveUploadChildren()
        {
            //if (ParentMap.Children.Contains(labelLayer))
            //    ParentMap.Children.Remove(labelLayer);

            //if (labelLayer.Children.Contains(tbCoordinates))
            //    labelLayer.Children.Remove(tbCoordinates);
        }




        //#region IMapControl<Map> Members

        //string mapName = string.Empty;
        //public string MapName
        //{
        //    get { return mapName; }
        //    set
        //    {
        //        mapName = value;
        //        setMapInstance(MapName);
        //    }
        //}

        //public Map MapInstance { get; set; }

        //private void setMapInstance(string mapname)
        //{
        //    ParentMap = (Map) Utilities.FindVisualChildByName<MapCore>(Application.Current.RootVisual, mapname);

        //    //MapInstance = Utilities.FindVisualChildByName<Map>(Application.Current.RootVisual, mapname);
        //}

        //#endregion

        #region IDisposable Members

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
